<template>
  <div v-if="!isHeaderDuplicate" class="header">
    <header class="sticky top-0 z-100">
      <nav class="bg-white border-gray-200 border-b shadow-sm dark:bg-gray-900 dark:border-gray-700">
        <div class="max-w-screen-xl flex flex-wrap items-center justify-between mx-auto p-4">
          <!-- LOGO -->
          <a href="/" class="flex items-center">
            <img src="https://flowbite.com/docs/images/logo.svg" class="h-8 mr-3" alt="Flowbite Logo" />
            <span class="self-center text-2xl font-semibold whitespace-nowrap text-gray-800 dark:text-white">
              {{ $store.state.setting.blogName }}
            </span>
          </a>

          <div class="flex items-center md:order-2">
            <div class="flex mr-3 relative">
              <!-- 搜索按钮 -->
              <button type="button" @click="toggleSearchPopup"
                      class="text-gray-700 hover:bg-gray-100 focus:outline-none focus:ring-4 focus:ring-gray-200 rounded-lg text-sm p-2.5 mr-1 dark:text-gray-300 dark:hover:bg-gray-700 dark:focus:ring-gray-600">
                <svg class="w-5 h-5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none"
                     viewBox="0 0 20 20">
                  <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="m19 19-4-4m0-7A7 7 0 1 1 1 8a7 7 0 0 1 14 0Z" />
                </svg>
                <span class="sr-only">搜索</span>
              </button>
              
              <!-- 主题切换按钮 - 只在非管理页面显示 -->
              <button v-if="!isAdminRoute" type="button" @click="toggleTheme"
                      class="text-gray-700 hover:bg-gray-100 focus:outline-none focus:ring-4 focus:ring-gray-200 rounded-lg text-sm p-2.5 mr-1 dark:text-gray-300 dark:hover:bg-gray-700 dark:focus:ring-gray-600">
                <!-- 白天模式图标 -->
                <svg v-if="isDarkMode" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                        d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"></path>
                </svg>
                <!-- 黑夜模式图标 -->
                <svg v-else class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                        d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"></path>
                </svg>
                <span class="sr-only">切换主题</span>
              </button>
              <button data-collapse-toggle="navbar-search" type="button"
                      class="inline-flex items-center p-2 w-10 h-10 justify-center text-sm text-gray-700 rounded-lg md:hidden hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-200 dark:text-gray-300 dark:hover:bg-gray-700 dark:focus:ring-gray-600"
                      aria-controls="navbar-search" aria-expanded="false">
                <span class="sr-only">Open main menu</span>
                <svg class="w-5 h-5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none"
                     viewBox="0 0 17 14">
                  <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M1 1h15M1 7h15M1 13h15" />
                </svg>
              </button>
              
              <!-- 搜索弹出框 -->
              <div v-if="showingSearchPopup" class="search-popup-overlay fixed inset-0 z-50 flex items-start justify-center pt-20">
                <div class="search-popup bg-white rounded-lg shadow-lg w-full max-w-lg mx-auto">
                  <div class="relative p-1 border-b border-gray-200">
                    <div class="flex items-center p-1">
                      <svg class="w-5 h-5 text-gray-400 ml-2" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20">
                        <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m19 19-4-4m0-7A7 7 0 1 1 1 8a7 7 0 0 1 14 0Z" />
                      </svg>
                      <input type="text" v-model="searchQuery" @keyup.enter="performSearch" @keyup.esc="toggleSearchPopup" autofocus
                            class="flex-1 border-0 focus:ring-0 focus:outline-none text-gray-800 py-3 px-2 text-sm"
                            placeholder="输入关键词搜索文章..." />
                      <button @click="toggleSearchPopup" class="text-gray-400 hover:text-gray-600 px-2">
                        <svg class="w-4 h-4" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 14 14">
                          <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6" />
                        </svg>
                      </button>
                    </div>
                  </div>

                  <!-- 搜索结果区域 -->
                  <div class="py-2 px-4">
                    <!-- 搜索中加载状态 -->
                    <div v-if="searchLoading" class="py-8 text-center">
                      <div class="inline-block h-8 w-8 animate-spin rounded-full border-4 border-solid border-blue-600 border-r-transparent align-[-0.125em] motion-reduce:animate-[spin_1.5s_linear_infinite]" role="status">
                        <span class="!absolute !-m-px !h-px !w-px !overflow-hidden !whitespace-nowrap !border-0 !p-0 ![clip:rect(0,0,0,0)]">加载中...</span>
                      </div>
                      <p class="mt-2 text-gray-600">搜索中...</p>
                    </div>
                    
                    <div v-else-if="searchQuery && searchQuery.length > 0 && searchResults.length > 0" class="text-sm text-gray-600 mb-2">
                      <span>找到 <strong>{{ searchResults.length }}</strong> 篇包含 "<span class="bg-yellow-200 px-1">{{ searchQuery }}</span>" 的文章</span>
                    </div>
                    
                    <!-- 搜索结果列表 -->
                    <div v-if="!searchLoading && searchResults.length > 0" class="search-results">
                      <div v-for="(result, index) in searchResults" :key="index" 
                           class="search-result-item hover:bg-gray-100 rounded flex items-start py-3 border-b border-gray-200"
                           @click="goToSearchResult(result)">
                        <div class="mr-3">
                          <div class="w-16 h-16 bg-gray-100 rounded flex items-center justify-center overflow-hidden">
                            <img v-if="result.cover" :src="result.cover" alt="文章图片" class="w-full h-full object-cover" />
                            <div v-else class="w-16 h-16 bg-blue-500 text-white flex items-center justify-center">
                              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                              </svg>
                            </div>
                          </div>
                        </div>
                        <div class="flex-1">
                          <h4 class="text-blue-600 font-medium text-base mb-1" v-html="highlightMatchText(result.title, searchQuery)"></h4>
                          <div class="text-gray-500 text-xs flex items-center">
                            <span class="mr-2">{{ result.date }}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                    
                    <!-- 无结果或未搜索时的空状态 -->
                    <div v-else-if="!searchLoading && searchQuery && searchQuery.length > 0" class="py-8 text-center text-gray-500">
                      <svg class="w-12 h-12 mx-auto text-gray-400 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                      </svg>
                      <p>没有找到相关文章</p>
                      <p class="text-sm mt-1">请尝试其他关键词</p>
                    </div>
                    <div v-else-if="!searchLoading" class="py-8 text-center text-gray-500">
                      <svg class="w-12 h-12 mx-auto text-gray-400 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16l2.879-2.879m0 0a3 3 0 104.243-4.242 3 3 0 00-4.243 4.242zM21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                      </svg>
                      <p>请输入关键词搜索</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 登录按钮或用户头像展示 -->
            <span class="text-gray-700 hover:text-blue-600 dark:text-gray-300 dark:hover:text-blue-400" v-if="!isLogin" @click="$router.push('/login')">登录</span>
            <button type="button" v-else
                    class="flex mr-3 text-sm rounded-full md:mr-0 focus:ring-4 focus:ring-gray-200 dark:focus:ring-gray-600"
                    id="user-menu-button" aria-expanded="false" data-dropdown-toggle="user-dropdown"
                    data-dropdown-placement="bottom">
              <span class="sr-only">Open user menu</span>
              <!-- 用户登录头像 -->
              <img class="w-8 h-8 rounded-full" :src="$store.state.setting.avatar" alt="user photo">
            </button>
            <!-- Dropdown menu -->
            <div class="z-50 hidden my-4 text-base list-none bg-white divide-y divide-gray-200 rounded-lg shadow dark:bg-gray-800 dark:divide-gray-700"
                 id="user-dropdown">
              <ul class="py-2" aria-labelledby="user-menu-button">
                <li>
                  <a @click="enterBackend"
                     class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700">
                    <svg class="inline w-3 h-3 mb-2px mr-1 text-gray-700 dark:text-gray-300" aria-hidden="true"
                         xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20">
                      <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"
                            stroke-width="2"
                            d="M10 14v4m-4 1h8M1 10h18M2 1h16a1 1 0 0 1 1 1v11a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1Z" />
                    </svg>
                    进入后台
                  </a>
                </li>
                <li>
                  <a @click="logout"
                     class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700">
                    <svg class="inline w-3 h-3 mb-2px mr-1 text-gray-700 dark:text-gray-300" aria-hidden="true"
                         xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16">
                      <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"
                            stroke-width="2"
                            d="M4 8h11m0 0-4-4m4 4-4 4m-5 3H3a2 2 0 0 1-2-2V3a2 2 0 0 1 2-2h3" />
                    </svg>
                    退出登录
                  </a>
                </li>
              </ul>
            </div>
          </div>
          <div class="items-center justify-between hidden w-full md:flex md:w-auto md:order-1" id="navbar-search">
            <ul
                class="flex flex-col p-4 md:p-0 mt-4 font-medium border border-gray-200 rounded-lg bg-gray-50 md:flex-row md:space-x-8 md:mt-0 md:border-0 md:bg-white dark:bg-gray-800 dark:border-gray-700 md:dark:bg-gray-900">
              <li>
                <a @click="$router.push('/')" :class="[isActive('/') ? 'text-blue-600 dark:text-blue-400' : 'text-gray-700 dark:text-gray-300']"
                   class="block py-2 pl-3 pr-4 rounded md:bg-transparent md:p-0 cursor-pointer hover:text-blue-600 dark:hover:text-blue-400" aria-current="page">
                  首页
                </a>
              </li>
              <li>
                <a @click="$router.push('/popular')"
                   :class="[isActive('/popular') ? 'text-blue-600 dark:text-blue-400' : 'text-gray-700 dark:text-gray-300']"
                   class="block py-2 pl-3 pr-4 rounded hover:bg-gray-100 md:hover:bg-transparent md:hover:text-blue-600 md:p-0 cursor-pointer dark:hover:bg-gray-700 dark:hover:text-blue-400">
                  热门
                </a>
              </li>
              <li>
                <a @click="$router.push('/category')"
                   :class="[isActive('/category') ? 'text-blue-600 dark:text-blue-400' : 'text-gray-700 dark:text-gray-300']"
                   class="block py-2 pl-3 pr-4 rounded hover:bg-gray-100 md:hover:bg-transparent md:hover:text-blue-600 md:p-0 cursor-pointer dark:hover:bg-gray-700 dark:hover:text-blue-400">
                  分类
                </a>
              </li>
              <li>
                <a @click="$router.push('/tag')"
                   :class="[isActive('/tag') ? 'text-blue-600 dark:text-blue-400' : 'text-gray-700 dark:text-gray-300']"
                   class="block py-2 pl-3 pr-4 rounded hover:bg-gray-100 md:hover:bg-transparent md:hover:text-blue-600 md:p-0 cursor-pointer dark:hover:bg-gray-700 dark:hover:text-blue-400">
                  标签
                </a>
              </li>
              <li>
                <a @click="$router.push('/archive')"
                   :class="[isActive('/archive') ? 'text-blue-600 dark:text-blue-400' : 'text-gray-700 dark:text-gray-300']"
                   class="block py-2 pl-3 pr-4 rounded hover:bg-gray-100 md:hover:bg-transparent md:hover:text-blue-600 md:p-0 cursor-pointer dark:hover:bg-gray-700 dark:hover:text-blue-400">
                  归档
                </a>
              </li>
              <li>
                <a @click="$router.push('/notices')"
                   :class="[isActive('/notices') ? 'text-blue-600 dark:text-blue-400' : 'text-gray-700 dark:text-gray-300']"
                   class="block py-2 pl-3 pr-4 rounded hover:bg-gray-100 md:hover:bg-transparent md:hover:text-blue-600 md:p-0 cursor-pointer dark:hover:bg-gray-700 dark:hover:text-blue-400">
                  公告
                </a>
              </li>
            </ul>
          </div>
        </div>
      </nav>

      <!-- 公告栏 -->
      <div class="max-w-screen-xl mx-auto">
        <NoticesList />
      </div>

      <!-- 退出登录 modal -->
      <div id="logout-modal" tabindex="-1"
           class="fixed top-0 left-0 right-0 z-50 hidden p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-[calc(100%-1rem)] max-h-full">
        <div class="relative w-full max-w-md max-h-full">
          <div class="relative bg-gray-800 rounded-lg shadow dark:bg-gray-700">
            <button type="button"
                    class="absolute top-3 right-2.5 text-gray-400 bg-transparent hover:bg-gray-700 hover:text-gray-300 rounded-lg text-sm w-8 h-8 ml-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white"
                    data-modal-hide="logout-modal">
              <svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none"
                   viewBox="0 0 14 14">
                <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6" />
              </svg>
              <span class="sr-only">Close modal</span>
            </button>
            <div class="p-6 text-center">
              <svg class="mx-auto mb-4 text-gray-400 w-12 h-12 dark:text-gray-200" aria-hidden="true"
                   xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20">
                <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M10 11V6m0 8h.01M19 10a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
              </svg>
              <h3 class="mb-5 text-lg font-normal text-gray-500 dark:text-gray-400">是否退出登录?</h3>
              <button @click="logout" data-modal-hide="logout-modal" type="button"
                      class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800 font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center mr-2">
                确认
              </button>
              <button data-modal-hide="logout-modal" type="button"
                      class="text-gray-500 bg-gray-800 hover:bg-gray-700 focus:ring-4 focus:outline-none focus:ring-gray-700 rounded-lg border border-gray-700 text-sm font-medium px-5 py-2.5 hover:text-white dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600 dark:hover:bg-gray-600 dark:focus:ring-gray-600">
                取消
              </button>
            </div>
          </div>
        </div>
      </div>
    </header>
  </div>
</template>

<script setup>
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { ref, computed, onMounted, onBeforeUnmount, watch, onUnmounted, nextTick } from 'vue'
import { showModel, showMessage } from '@/composables/util'
import { initDropdowns, initCollapses, initModals } from 'flowbite'
import NoticesList from '@/components/notices/NoticesList.vue'
import { searchArticles, searchArticlesPublic } from '@/api/frontend/article'
import axios from "@/axios";
import { Modal } from 'flowbite';

// 主题设置
const isDarkMode = ref(localStorage.getItem('theme') === 'dark')

// 初始化主题设置
const initThemeState = () => {
  // 获取本地存储的主题
  const savedTheme = localStorage.getItem('theme');
  
  // 初始化暗黑模式状态
  isDarkMode.value = savedTheme === 'dark' || 
    (!savedTheme && window.matchMedia('(prefers-color-scheme: dark)').matches);
}

// 切换主题
const toggleTheme = () => {
  isDarkMode.value = !isDarkMode.value;
  
  if (isDarkMode.value) {
    document.documentElement.classList.add('dark');
    localStorage.setItem('theme', 'dark');
  } else {
    document.documentElement.classList.remove('dark');
    localStorage.setItem('theme', 'light');
  }
};

// 简单的事件总线，用于组件间通信
const eventBus = {
  events: {},
  emit(event, data) {
    if (this.events[event]) {
      this.events[event].forEach(callback => callback(data));
    }
    // 同时存储到localStorage，用于跨页面通信
    localStorage.setItem('weblog_event_' + event, JSON.stringify({
      data,
      timestamp: new Date().getTime()
    }));
  },
  on(event, callback) {
    if (!this.events[event]) {
      this.events[event] = [];
    }
    this.events[event].push(callback);
  },
  off(event, callback) {
    if (this.events[event]) {
      this.events[event] = this.events[event].filter(cb => cb !== callback);
    }
  }
};

// 将事件总线挂载到window对象，方便跨组件访问
window.weblogEventBus = eventBus;

// 防抖函数
function debounce(fn, delay) {
  let timer = null
  return function(...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 使用一个全局标志来防止重复渲染
const isHeaderDuplicate = ref(false);
const headerIdentifier = 'global-header-rendered';

onMounted(() => {
  initCollapses()
  initDropdowns()
  initModals()
  
  // 初始化主题
  initThemeState()
  
  document.addEventListener('click', (e) => {
    const searchPopup = document.querySelector('.search-popup')
    const searchButton = document.querySelector('.text-gray-700.hover\\:bg-gray-100')
    
    if (showingSearchPopup.value && searchPopup && !searchButton.contains(e.target) && !searchPopup.contains(e.target)) {
      showingSearchPopup.value = false
    }
  })

  // 检查是否已经存在header
  if (window[headerIdentifier]) {
    isHeaderDuplicate.value = true;
  } else {
    window[headerIdentifier] = true;
  }
})

onUnmounted(() => {
  // 当组件卸载时，重置标志
  window[headerIdentifier] = false;
})

const store = useStore()
const route = useRoute()
const router = useRouter()

const currPath = ref(route.path)
const isLogin = computed(() => Object.keys(store.state.user).length > 0)
// 使用 Vuex 中的用户信息获取角色，假设 user.role 为 1 表示管理员，其它为普通用户
const userRole = computed(() => store.state.user?.role)

// 搜索相关变量和方法
const searchQuery = ref('')
const showingSearchPopup = ref(false)
const searchResults = ref([])
const searchLoading = ref(false)

const toggleSearchPopup = () => {
  showingSearchPopup.value = !showingSearchPopup.value
  if (showingSearchPopup.value) {
    // 当弹出框打开时，重置搜索内容
    searchQuery.value = ''
    searchResults.value = []
    // 添加ESC键监听
    document.addEventListener('keydown', handleKeyDown)
  } else {
    // 当弹出框关闭时，移除ESC键监听
    document.removeEventListener('keydown', handleKeyDown)
  }
}

const handleKeyDown = (e) => {
  // 按ESC键关闭搜索
  if (e.key === 'Escape' && showingSearchPopup.value) {
    showingSearchPopup.value = false;
  }
  
  // 按Ctrl+K打开搜索
  if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
    e.preventDefault();
    toggleSearchPopup();
  }
};

// 调用后端API进行搜索
const fetchSearchResults = (query) => {
  if (!query || !query.trim()) {
    searchResults.value = []
    return
  }
  
  searchLoading.value = true
  
  // 准备搜索参数 - 由于后端不支持标题搜索，我们获取所有文章然后在前端过滤
  const params = {
    current: 1,
    size: 50 // 增大返回数量，确保能获取足够多的文章用于前端过滤
  }
  
  console.log('发送搜索请求，参数:', params)
  
  // 使用不携带Token的搜索函数
  searchArticlesPublic(params)
    .then(res => {
      console.log('搜索API响应:', res)
      if (res.success && res.data && res.data.records) {
        // 在前端过滤包含搜索关键词的文章
        const filteredResults = res.data.records.filter(item => 
          item.title && item.title.toLowerCase().includes(query.toLowerCase())
        );
        
        console.log(`前端过滤：从${res.data.records.length}篇文章中找到${filteredResults.length}篇匹配"${query}"的文章`);
        
        // 转换返回结果为所需格式
        searchResults.value = filteredResults.map(item => {
          // 确保所有必要的字段都存在，对缺失的字段提供默认值
          return {
            id: item.id,
            title: item.title || '无标题',
            date: item.createTime || item.updateTime || '未知日期',
            url: `/article/detail?articleId=${item.id}`,
            cover: item.titleImage || item.cover || '' // 使用titleImage或cover字段作为封面
          };
        });
        
        console.log('处理后的搜索结果:', searchResults.value)
      } else {
        searchResults.value = []
        console.error('搜索结果格式错误:', res)
      }
    })
    .catch(err => {
      console.error('搜索失败:', err)
      searchResults.value = []
    })
    .finally(() => {
      searchLoading.value = false
    })
}

// 监听搜索输入变化，实时搜索
const debouncedFetch = debounce((query) => {
  if (query && query.trim()) {
    // 使用真实API调用替代模拟数据
    fetchSearchResults(query)
  } else {
    searchResults.value = []
  }
}, 500) // 500ms防抖

watch(searchQuery, (newQuery) => {
  debouncedFetch(newQuery)
}, { immediate: true })

const performSearch = () => {
  if (searchQuery.value.trim()) {
    // 如果有搜索结果，跳转到第一个结果
    if (searchResults.value.length > 0) {
      goToSearchResult(searchResults.value[0])
    } else {
      // 无结果时跳转到搜索页
      router.push({
        path: '/search',
        query: { q: searchQuery.value }
      })
    }
    
    // 关闭搜索弹框
    toggleSearchPopup()
  }
}

const goToSearchResult = (result) => {
  // 关闭搜索弹框
  toggleSearchPopup();
  
  const currentRoute = router.currentRoute.value;
  const targetPath = result.url;
  
  // 提取目标文章ID
  const urlParams = new URLSearchParams(targetPath.split('?')[1]);
  const articleId = urlParams.get('articleId');
  
  // 检查当前是否在文章详情页，并且要跳转到另一篇文章
  if (currentRoute.path === '/article/detail') {
    // 如果当前文章ID和目标文章ID不同，需要强制刷新
    if (currentRoute.query.articleId !== articleId) {
      console.log('当前已在文章详情页，强制加载新文章：', articleId);
      
      // 尝试通过事件总线通知文章详情页重新加载
      if (window.weblogEventBus) {
        window.weblogEventBus.emit('reload-article', {
          articleId: articleId
        });
        
        // 同时还是通过router进行跳转
        router.push(targetPath);
      } else {
        // 降级方案：使用location.href直接加载新页面
        window.location.href = targetPath;
      }
      return;
    }
  }
  
  // 正常情况下使用vue-router跳转
  router.push(targetPath);
}

// 高亮匹配文本
const highlightMatchText = (text, query) => {
  if (!query || !text) return text;
  try {
    // 转义正则表达式特殊字符
    const escapedQuery = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    const regex = new RegExp(`(${escapedQuery})`, 'gi');
    return text.replace(regex, '<span class="bg-yellow-200">$1</span>');
  } catch (e) {
    console.error('高亮处理错误:', e);
    return text;
  }
}

const logout = () => {
  console.log('登出')
  store.dispatch('logout')
  showMessage('退出登录成功', 'success')
}

const enterBackend = () => {
  // 从 localStorage 中获取角色信息
  const role = localStorage.getItem('role')
  if (role === '1' || role === 1) {
    router.push('/admin')
  } else {
    router.push('/user')
  }
}

// 添加活动状态判断函数
const isActive = (path) => {
  // 精确匹配首页
  if (path === '/' && route.path === '/') {
    return true
  }
  // 其他页面使用 startsWith 进行匹配，支持子路径
  if (path !== '/' && route.path.startsWith(path)) {
    return true
  }
  return false
}

// 监听路由变化，更新当前路径
watch(() => route.path, (newPath) => {
  currPath.value = newPath
})

// 判断当前路由是否为管理页面或用户后台页面
const isAdminRoute = computed(() => {
  return route.path.startsWith('/admin') || route.path.startsWith('/user');
});
</script>

<style scoped>
.container {
  max-width: 1260px;
}

.header-container {
  border-bottom: solid 1px var(--el-menu-border-color);
}

.el-menu--horizontal {
  border-bottom: 0;
}

.el-menu {
  height: 55px;
}

.el-header {
  border-bottom: 1px solid #dcdfe6;
  height: 55px;
}

.navbar-wrapper {
  height: 55px;
}

.logo-img {
  height: 40px;
}

.logo-container>a {
  height: 28px;
  width: 128px;
}

.title {
  font-size: 1.6rem;
  font-weight: 800;
}

.title-li:hover {
  border-bottom: 1px solid #fff !important;
}

.bg-gray-hover:hover {
  border-bottom: 1px solid #fff !important;
  background-color: #f4f4f5 !important;
}

.search-popup-overlay {
  background-color: transparent;
}

.search-popup {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e5e7eb;
  animation: fadeIn 0.2s ease-in-out;
  max-height: 80vh;
  overflow-y: auto;
  width: 584px;
}

.search-popup input {
  font-size: 14px;
}

.search-popup .search-result-item:last-child {
  border-bottom: none;
}

.search-result-item {
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.search-result-item:hover {
  background-color: #f8fafc;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-20px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>
